﻿
using ConfClient;
using SuperSocket.Client;
using System.Collections.Concurrent;
using System.IO;
using System.Net;
using System.Net.Sockets;
using gpb = global::Google.Protobuf;

namespace SvCore.Tcp;

public static class MyTcpClient
{
    public static ConcurrentQueue<MyPackage> ListMsg = new ConcurrentQueue<MyPackage>();
    public static IEasyClient<MyPackage> Client;
    public static bool IsConneted = false;

    public static async void Start()
    {
        Client = new EasyClient<MyPackage>(new MyPackageFilter()).AsClient();

        if (!await Client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 8888)))
        {
            return;
        }
        IsConneted = true;
        while (true)
        {
            var p = await Client.ReceiveAsync();

            if (p == null) // connection dropped
                break;

            ListMsg.Enqueue(p);
        }
    }
    public static void Send<T>(T msg, EProtocolResult ecode = EProtocolResult.成功) where T : gpb.IMessage
        => Send(MyPackage.From(msg, ecode));
    public static void Send(MyPackage pack)
    {
        try
        {
            Client.SendAsync(pack.Encode());
        }
        catch
        {
        }
    }
}
